import operator,random,timeit

def sort_data(data_list,sort_code,reverse=True):
    if len(data_list) > 100000:
        return  sorted(data_list, key=lambda x: x[sort_code], reverse=reverse)
    return sorted(data_list, key=operator.itemgetter(sort_code), reverse=reverse)

if __name__ == "__main__":
    # a = [{'name':'john', 'rate':15, 'age':20}, {'name':'jane', 'rate': 12}, {'name':'dave', 'rate': 10}]
    # print(a)
    # c = sort_data(a,'rate',False)
    # print(c)

    data_list = [{'click_rate': random.random()} for _ in range(10000)]

    # 使用timeit.timeit来测试排序操作的执行时间
    sort_time = timeit.timeit('sorted(data_list, key=lambda x: x["click_rate"], reverse=True)',
                              globals=globals(),
                              number=1)

    print(f"Sorting the list took {sort_time:.6f} seconds use lambda")

    sort_time = timeit.timeit('sorted(data_list, key=operator.itemgetter("click_rate"), reverse=True)',
                              globals=globals(),
                              number=1)

    print(f"Sorting the list took {sort_time:.6f} seconds use operator.itemgetter")